package com.example.config.security.hanlder;
import com.example.util.JSONAuthentication;
import com.example.vo.ResultVo;
import com.example.vo.ResultVoEnum;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Service;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义认证入口点实现 （用于处理匿名用户的异常）
 * @author wsl
 */
@Service("authenticationEntryPoint")
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        Object exception = request.getAttribute("javax.servlet.error.exception");
        ResultVoEnum resultVoEnum = null;
        if(e instanceof InsufficientAuthenticationException){
            resultVoEnum = ResultVoEnum.USER_NOT_LOGIN;
        }else if(e instanceof CredentialsExpiredException){
            resultVoEnum = ResultVoEnum.USER_LOGIN_EXPIRED;
        }else {
            resultVoEnum = ResultVoEnum.ERROR;
        }
        JSONAuthentication.WriteJSON(request,response, resultVoEnum);
    }
}
